package com.htdata.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import jxl.read.biff.BiffException;

public class ExcelUtil {
	// 根据excel文件获取数据
	public static List createPropertyByExcel() throws IOException, BiffException {
		System.out.println("***************开始解析EXCEL***************");
		List list = new ArrayList();
		try {
			String path = ExcelUtil.class.getClassLoader().getResource("").getPath();
			File file = new File(path+"/excel");
			System.out.println("===========>EXCEL文件路径："+path+"/excel");
			// Excel下文件个数
			File[] fileList = file.listFiles();
			if (fileList.length > 0) {
				for (int i = 0; i < fileList.length; i++) {
					//读取excel
					System.out.println("===========>EXCEL名称："+fileList[i].getName());
					XSSFWorkbook rwb = new XSSFWorkbook(new FileInputStream(fileList[i]));
					XSSFSheet st = rwb.getSheetAt(0);// 得到所有Excel中页的列表
					String iotid = "", apikey = "", equipment = "";
				    Map map = new HashMap();
					for (int k = 1; k < st.getLastRowNum()+1; k++) {
						Row row = st.getRow(k);  
						Cell cell = row.getCell(1, Row.CREATE_NULL_AS_BLANK);
						if (cell == null || cell.equals("") || cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) {
							equipment = equipment + "," + row.getCell(2);
							continue;
						}else{
							//执行到下一个iot
							if(equipment.indexOf(",") != -1){
								map.put("equipment", equipment);
								Map tempMap = new HashMap();
								tempMap.putAll(map);
								list.add(tempMap);
								System.out.println("===========>网关【"+tempMap.get("iot")+"】导入成功，该网关下有："+equipment.split(",").length+"条数据");
							}
							iotid = row.getCell(0).getRichStringCellValue().getString(); 
							apikey =  row.getCell(1).getRichStringCellValue().getString();
							equipment =  row.getCell(2).getRichStringCellValue().getString();
							map.put("iot", iotid);
							map.put("apikey", apikey);
						}
						
					}
					//最后一组
					Map lastMap = new HashMap();
					lastMap.put("iot", iotid);
					lastMap.put("apikey", apikey);
					lastMap.put("equipment", equipment);
					list.add(lastMap);
					System.out.println("===========>网关【"+lastMap.get("iot")+"】导入成功，该网关下有：" + equipment.split(",").length + "条数据");
					
				}
			}
		} catch (IOException e) {
			System.out.println("***************Excel解析异常***************");
			e.printStackTrace();
		} finally {
			System.out.println("***************EXCEL解析完成，共有【"+list.size()+"】家企业***************");
			return list;
		}
	}
}
